float4x4 WVP;
float3x3 World;

texture2D Texture;
sampler2D texSampler = sampler_state
{
	Texture = <Texture>;
	MinFilter = anisotropic;
	MagFilter = anisotropic;
	MipFilter = linear;
	AddressU = wrap;
	AddressV = wrap;
	MaxAnisotropy = 16;
};

texture2D BumpTexture;
sampler2D bumpSampler = sampler_state
{
	Texture = <BumpTexture>;
	MinFilter = Point;
	MagFilter = Point;
	MipFilter = linear;
	AddressU = wrap;
	AddressV = wrap;
	MaxAnisotropy = 16;
};

texture2D PalateTexture;
sampler2D palateSampler = sampler_state
{
	Texture = <PalateTexture>;
	AddressU = mirror;
	AddressV = mirror;
};

struct VSInput
{
	float4 Position : POSITION0;
	float2 Texture : TEXCOORD0;
	float3 Normal : NORMAL0;
};

struct VSOutput
{
	float4 Position : POSITION0;
	float2 Texture : TEXCOORD1;
	float3 PositionO : TEXCOORD2;
	float3 Normal : NORMAL;
	float2 Depth : TEXCOORD3;
};

struct PSInput
{
	float2 Texture : TEXCOORD1;
	float3 Position : TEXCOORD2;
	float3 Normal : NORMAL;
	float2 Depth : TEXCOORD3;
};

struct PSOutput
{
	float4 Color : COLOR0;
	float4 Normal : COLOR1;
	float4 Depth : COLOR2;
};

VSOutput VSFunction(VSInput input)
{
	VSOutput output;

	output.Position = mul(input.Position, WVP);

	output.Normal = mul(input.Normal, World);

	output.PositionO = input.Position.xyz;

	output.Texture = input.Texture;

	output.Depth.xy = output.Position.zw;
  
	return output;
}

float4 getTexture(float3 position) 
{
	float2 t = float2(position.x + position.y, position.y + position.z);
	float4 sampleA = tex2D(texSampler, t);
	t += float2(0.3, 0.923);
	float4 sampleB = tex2D(texSampler, t/3.3);
	t -= float2(0.343, 0.327);
	float4 sampleC = tex2D(texSampler, t/15.9);
	return 0.25 * sampleA + 0.45*sampleB + 0.3 * sampleC;
}

float4 getNormal(float3 position)
{
	float2 t = float2(position.x + position.y, position.y + position.z);
	float4 sampleA = tex2D(bumpSampler, t * 1.5) * 2 - 1;
	/*
	t += float2(0.3, 0.923);
	float4 sampleB = tex2D(bumpSampler, t/3.3) * 2 - 1;
	t -= float2(0.343, 0.327);
	float4 sampleC = tex2D(bumpSampler, t/15.9) * 2 - 1;
	float4 n = 0.25 * sampleA + 0.45*sampleB + 0.3 * sampleC;
	*/
	float4 n = sampleA;
	n.w = 1;
	return normalize(n);
}

PSOutput PSFunction(PSInput input)
{
	PSOutput ret;
	float4 color = tex2D(palateSampler, (input.Texture + float2(0.5, 0.5)) / 16.0);
	float4 scale;
	if(length(color.xyz) < 0.1) {
		scale = float4(0.25, 0.25, 0.25, 1);
	}
	else {
		scale = color*3;
	}
	ret.Color = getTexture(input.Position) * scale;
	float4 normal = float4(input.Normal, 1) + getNormal(input.Position) * 0.15;
	normal.w = 1;
	ret.Normal = normalize(normal)/2 + float4(0.5, 0.5, 0.5, 0.5);
	float depth = input.Depth.x / input.Depth.y;
	ret.Depth = float4(depth, 0, 0, 0);
	return ret;
}

technique StaticMap
{
	pass StaticMap
	{
		VertexShader = compile vs_3_0 VSFunction();
		PixelShader = compile ps_3_0 PSFunction();
	}
}